package com.yzd.xander.action;

import com.opensymphony.xwork2.ActionSupport;
import com.yzd.xander.entity.Users;
import com.yzd.xander.service.UserService;
import org.apache.struts2.convention.annotation.*;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by YE on 2018-06-07.
 */
@Controller
@Scope("prototype")
@ParentPackage("struts-default")
@Namespace("/user")
@Results({@Result(name = "success", type = "redirect", location = "../index.jsp"),
        @Result(name = "loginerror", location = "../login.jsp"),
        @Result(name = "registererror", location = "../register.jsp"),
        @Result(name = "error", type = "redirect", location = "../index.jsp")})
public class UserAction extends ActionSupport implements ServletRequestAware, ServletResponseAware {
    @Autowired
    private UserService userService;
    private HttpServletRequest request;
    private HttpServletResponse response;

    @Action("login")
    public String login() {
        Users user = new Users();
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        user.setUsername(username);
        user.setPassword(password);
        user = userService.selectUser(user);
        if (user != null) {
            request.getSession().setAttribute("user", user);
            return SUCCESS;
        } else {
            request.setAttribute("message", "用户名或密码错误");
            return "loginerror";
        }
    }

    @Action("logout")
    public String logout() {
        request.getSession().invalidate();
        return SUCCESS;
    }

    @Action("register")
    public String register() {
        Users user = null;
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if (!userService.isExist(username)) {
            user = new Users();
            user.setUsername(username);
            user.setPassword(password);
            if (userService.addUser(user) > 0) {
                return SUCCESS;
            } else {
                return ERROR;
            }
        } else {
            request.setAttribute("message", "用户名已存在");
            return "registererror";
        }
    }

    @Override
    public void setServletRequest(HttpServletRequest httpServletRequest) {
        this.request = httpServletRequest;
    }

    @Override
    public void setServletResponse(HttpServletResponse httpServletResponse) {
        this.response = httpServletResponse;
    }
}
